package mcg.android.superlista.produto;

import mcg.android.superlista.R;
import mcg.android.superlista.R.id;
import mcg.android.superlista.R.layout;
import mcg.android.superlista.db.DBAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ProductDetails extends Activity {
	private EditText mNameText;
	private Long mRowId;
	private DBAdapter dbAdapter;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		dbAdapter = new DBAdapter(this);
		dbAdapter.open();
		setContentView(R.layout.product_edit);
		mNameText = (EditText) findViewById(R.id.product_edit_name);

		Button confirmButton = (Button) findViewById(R.id.product_edit_button);
		mRowId = null;
		Bundle extras = getIntent().getExtras();
		mRowId = (bundle == null) ? null : (Long) bundle
				.getSerializable(DBAdapter.KEY_ROWID);
		if (extras != null) {
			mRowId = extras.getLong(DBAdapter.KEY_ROWID);
		}
		populateFields();
		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setResult(RESULT_OK);
				finish();
			}

		});
		
		Button cancelButton = (Button) findViewById(R.id.product_cancel_button);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private void populateFields() {
		if (mRowId != null) {
			Cursor product = dbAdapter.fetchProduct(mRowId);
			startManagingCursor(product);
			mNameText.setText(product.getString(product
					.getColumnIndexOrThrow(DBAdapter.KEY_NAME)));
		}
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		saveState();
		outState.putSerializable(DBAdapter.KEY_ROWID, mRowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	private void saveState() {
		String name = mNameText.getText().toString();

		if (mRowId == null) {
			long id = dbAdapter.createProduct(name);
			if (id > 0) {
				mRowId = id;
			}
		} else {
			dbAdapter.updateProduct(mRowId, name);
		}
	}

}
